/* Copyright (c) 2012 swing-on-fire Team
 * 
 * This file is part of Swing-On-Fire (http://code.google.com/p/swing-on-fire), licensed under the terms of the MIT
 * License (MIT).
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
package com.google.code.swingonfire.animation;

/**
 * Executes animations in parallel.
 * 
 * @author thred
 */
public class ParallelAnimation implements DurableAnimation
{

    private static class RunningAnimation
    {
        private final Animation animation;

        private double nextTime = 0;

        public RunningAnimation(Animation animation)
        {
            super();

            this.animation = animation;
        }

        public double getDuration()
        {
            return (animation instanceof DurableAnimation) ? ((DurableAnimation) animation).getDuration() : Double.NaN;
        }

        public void animationReset() throws AnimationException
        {
            try
            {
                animationReset();
            }
            catch (Exception e)
            {
                nextTime = Double.NaN;
                throw new AnimationResetException(animation, "Invocation of animationReset caused exception", e);
            }

            nextTime = 0;
        }

        public double animationStep(double delay, double time) throws AnimationException
        {
            if (Double.isNaN(nextTime))
            {
                return Double.NaN;
            }

            if (time < nextTime)
            {
                return nextTime - time;
            }

            double duration =
                (animation instanceof DurableAnimation) ? ((DurableAnimation) animation).getDuration() : Double.NaN;
            double fraction = AnimationUtil.toFraction(time, duration);

            try
            {
                delay = AnimationUtil.animationResult(animation.animationStep(delay, time, fraction), time, duration);
            }
            catch (AnimationAbortedException e)
            {
                delay = Double.NaN;
            }
            catch (Exception e)
            {
                throw new AnimationStepException(animation, "Invocation of animationStep caused exception", e);
            }

            if (!AnimationUtil.isUndefined(duration))
            {
                if (duration == 0)
                {
                    delay = Double.NaN;
                }
                else
                {
                    if (time >= duration)
                    {
                        delay = Double.NaN;
                    }
                }
            }

            if (AnimationUtil.isFinished(delay))
            {
                nextTime = Double.NaN;
            }

            return delay;
        }

    }

    public static Animation parallel(Animation... animations)
    {
        if ((animations == null) || (animations.length == 0))
        {
            throw new IllegalArgumentException("At least one animation expected");
        }

        if (animations.length == 1)
        {
            return animations[0];
        }

        return new ParallelAnimation(animations);
    }

    private final RunningAnimation[] runningAnimations;

    private double duration;

    protected ParallelAnimation(Animation[] animations)
    {
        super();

        runningAnimations = new RunningAnimation[animations.length];

        for (int i = 0; i < animations.length; i += 1)
        {
            runningAnimations[i] = new RunningAnimation(animations[i]);
        }

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void animationReset()
    {
        duration = 0;

        for (RunningAnimation runningAnimation : runningAnimations)
        {
            try
            {
                runningAnimation.animationReset();
            }
            catch (Exception e)
            {
                throw new AnimationRuntimeException(runningAnimation.animation, "Unhandled exception in animation", e);
            }

            double currentDuration = runningAnimation.getDuration();

            if ((!Double.isNaN(duration)) && (!AnimationUtil.isUndefined(currentDuration)))
            {
                duration += currentDuration;
            }
            else
            {
                duration = Double.NaN;
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double getDuration()
    {
        return duration;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double animationStep(double delay, double time, double fraction)
    {
        double minDelay = Double.NaN;

        for (RunningAnimation runningAnimation : runningAnimations)
        {
            try
            {
                delay = runningAnimation.animationStep(delay, time);
            }
            catch (AnimationException e)
            {
                throw new AnimationRuntimeException(runningAnimation.animation, "Unhandled exception in animation", e);
            }

            if (((Double.isNaN(minDelay)) || (delay < minDelay)) && (!AnimationUtil.isFinished(delay)))
            {
                minDelay = delay;
            }
        }

        return minDelay;
    }

}
